from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI
import redRi18n
_ = redRi18n.get_(package = 'base')

class sbpComp(OWRpy):
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
        #create a R variable in the R session. 
        self.setRvariableNames(['table', 'V'])
        
        #create initial python variables
        self.isfirst = 'yes'
        self.classes = None
        self.savedData = None
        
        # Define the inputs that this widget will accept
        self.inputs.addInput('Data Table', 'Data Table', signals.base.RDataFrame, self.processDF)
        
        # Define the outputs of this widget
        self.outputs.addOutput('Data Table', 'Sequential binary partition', signals.base.RDataFrame)

        #START THE GUI LAYOUT
        area = redRGUI.base.widgetBox(self.controlArea,orientation='vertical') 
        self.dataTable = redRGUI.base.table(area, label = 'Data Table', rows = 1, columns = 1) #default table, if not connected
        self.connect(self.dataTable, SIGNAL("cellClicked(int, int)"), self.cellClicked)
        self.lock = redRGUI.base.checkBox(area, label='Lock', buttons = ['Lock the widget if you don\'t want the SBP to change each time new data is parsed (locked if checked).'], setChecked = 'FALSE')
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitTable, processOnInput=True)

    def processDF(self, data):
        if not self.require_librarys(["compositions"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.data = data.getData()
            self.savedData = data
            if self.lock.getChecked():
                print 'Locked: will not populate table.'
            else:
                self.populateTable()
        else:
            return

    def populateTable(self):
        self.pythonData = self.R('as.data.frame(gsi.ilrBase2signary(t(ilrBase('+self.savedData.getData()+'))))')
        print 'PYTHONDATA: ', self.pythonData
        print 'TYPE: ', type(self.pythonData)
        self.colNames=self.R('colnames('+self.data+')') #get the column names
        self.dataTable.setTable(self.pythonData)
        self.dataTable.setHorizontalHeaderLabels(self.colNames) # Push column names to the table
        self.connect(self.dataTable, SIGNAL("cellClicked(int, int)"), self.cellClicked)

    def cellClicked(self, row, col):
        print unicode(row), unicode(col)
        pass

    def onCellFocus(self, currentRow, currentCol, tb):
        if len(tb) == 0: return
        print 'cell on focus'
        item = tb.item(currentRow, currentCol)
        tb.editItem(item)
    
    def commitTable(self):
        #run through the table and make the output
        
        rowi = range(0, len(self.pythonData)-1)
        coli = range(0, len(self.pythonData))
            
        rownames = {}        
        colnames = {}
        rinsertion = []
        
        for j in coli:
            element = ''
            if colnames:
                element += colnames[unicode(j)]+'='
            if self.classes:
                element += self.classes[j-1][0]
            element += 'c('
            inserts = []
            for i in rowi:
                tableItem = self.dataTable.item(i,j)
                if tableItem == None:
                    inserts.append('NA')
                else:
                    try: #catch if the element can be coerced to numeric in the table
                        float(tableItem.text()) #will fail if can't be coerced to int 
                        inserts.append(unicode(tableItem.text()))
                    except:
                        if tableItem.text() == 'NA': 
                            inserts.append(unicode(tableItem.text()))
                            print 'set NA'
                        elif tableItem.text() == '1.#QNAN': 
                            inserts.append('NA') #if we read in some data
                            print 'set QNAN to NA'
                        else: 
                            inserts.append('"'+unicode(tableItem.text())+'"')
                            print unicode(tableItem.text())+' set as text'

            insert = ','.join(inserts)
            element += insert+')'
            if self.classes:
                element += self.classes[j-1][1]
            rinsertion.append(element)
            
        rinsert = ','.join(rinsertion)

        if len(rownames) > 0:
            rname = []
            for i in rowi:
                if rownames[unicode(i)] in rname:
                    rname.append(rownames[unicode(i)]+'_at_'+unicode(i))
                else:
                    rname.append(rownames[unicode(i)])
            rnf = '","'.join(rname)
            rinsert += ', row.names =c("'+rnf+'")' 
        self.R(self.Rvariables['table']+'<-data.frame('+rinsert+')', wantType = 'NoConversion')
        
        self.newData = signals.base.RDataFrame(self, data = self.Rvariables['table'], parent = self.Rvariables['table'])
        self.rSend('Data Table', self.newData)
        
        self.isfirst='no'